// repositories/article_repository.go
package repositories

import (
	"gorm_project/models"

	"gorm.io/gorm"
)

type ArticleRepository struct {
	*BaseRepository
}

func NewArticleRepository(db *gorm.DB) *ArticleRepository {
	return &ArticleRepository{
		BaseRepository: NewBaseRepository(db),
	}
}

func (r *ArticleRepository) Create(article *models.Article) error {
	return r.DB().Create(article).Error
}

func (r *ArticleRepository) FindByID(id uint) (*models.Article, error) {
	var article models.Article
	err := r.DB().Preload("User").Preload("Category").Preload("Tags").
		First(&article, id).Error
	return &article, err
}

func (r *ArticleRepository) FindPublished() ([]models.Article, error) {
	var articles []models.Article
	err := r.DB().Preload("User").Preload("Category").Preload("Tags").
		Where("status = ?", "published").
		Order("created_at DESC").
		Find(&articles).Error
	return articles, err
}

func (r *ArticleRepository) FindByCategory(categoryID uint) ([]models.Article, error) {
	var articles []models.Article
	err := r.DB().Preload("User").Preload("Category").Preload("Tags").
		Where("category_id = ? AND status = ?", categoryID, "published").
		Order("created_at DESC").
		Find(&articles).Error
	return articles, err
}

func (r *ArticleRepository) Update(article *models.Article) error {
	return r.DB().Save(article).Error
}

func (r *ArticleRepository) Delete(id uint) error {
	return r.DB().Delete(&models.Article{}, id).Error
}

func (r *ArticleRepository) IncreaseViews(id uint) error {
	return r.DB().Model(&models.Article{}).Where("id = ?", id).
		Update("views", gorm.Expr("views + ?", 1)).Error
}
